package tpdisenio2009.mvp.display;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import tpdisenio2009.model.beans.FantasyTeamPlayer;
import tpdisenio2009.model.beans.SoccerPlayer;

public class UpdateFantasyTeamViewImpl2 extends javax.swing.JDialog implements UpdateFantasyTeamView2 {

    private SoccerPlayer[] soccerPlayers = new SoccerPlayer[15];

    /** Creates new form CreateFantasyTeamViewImpl2 */
    public UpdateFantasyTeamViewImpl2(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();

        Dimension dim = this.getToolkit().getScreenSize();
        this.setLocation((dim.width - this.getWidth()) / 2,(dim.height - this.getHeight()) / 2);

        for (int i = 0; i < 15; i++) {
            soccerPlayers[i] = null;
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButtonExit = new javax.swing.JButton();
        jButtonSaveChange = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTableSoccerPlayers = new javax.swing.JTable();
        jLabel2 = new javax.swing.JLabel();
        jLabelGastado = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabelTeQuedan = new javax.swing.JLabel();
        jButtonQueryPlayers = new javax.swing.JButton();
        jLabelNameTeam = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(tpdisenio2009.Tpdisenio2009App.class).getContext().getResourceMap(UpdateFantasyTeamViewImpl2.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setName("Form"); // NOI18N

        jButtonExit.setText(resourceMap.getString("jButtonExit.text")); // NOI18N
        jButtonExit.setToolTipText(resourceMap.getString("jButtonExit.toolTipText")); // NOI18N
        jButtonExit.setName("jButtonExit"); // NOI18N

        jButtonSaveChange.setText(resourceMap.getString("jButtonSaveChange.text")); // NOI18N
        jButtonSaveChange.setName("jButtonSaveChange"); // NOI18N

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jPanel1.border.title"))); // NOI18N
        jPanel1.setName("jPanel1"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jTableSoccerPlayers.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {"Arquero", null, null, null},
                {"Defensor 1", null, null, null},
                {"Defensor 2", null, null, null},
                {"Defensor 3", null, null, null},
                {"Defensor 4", null, null, null},
                {"Volante 1", null, null, null},
                {"Volante 2", null, null, null},
                {"Volante 3", null, null, null},
                {"Delantero 1", null, null, null},
                {"Delantero 2", null, null, null},
                {"Delantero 3", null, null, null},
                {"Arquero Suplente", null, null, null},
                {"Defensor Suplente", null, null, null},
                {"Volante Suplente", null, null, null},
                {"Delantero Suplente", null, null, null}
            },
            new String [] {
                "Posición", "Jugador", "Club", "Cotización"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTableSoccerPlayers.setName("jTableSoccerPlayers"); // NOI18N
        jTableSoccerPlayers.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(jTableSoccerPlayers);
        jTableSoccerPlayers.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("jTableSoccerPlayers.columnModel.title0")); // NOI18N
        jTableSoccerPlayers.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("jTableSoccerPlayers.columnModel.title1")); // NOI18N
        jTableSoccerPlayers.getColumnModel().getColumn(2).setHeaderValue(resourceMap.getString("jTableSoccerPlayers.columnModel.title2")); // NOI18N
        jTableSoccerPlayers.getColumnModel().getColumn(3).setHeaderValue(resourceMap.getString("jTableSoccerPlayers.columnModel.title3")); // NOI18N

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        jLabelGastado.setFont(resourceMap.getFont("jLabelGastado.font")); // NOI18N
        jLabelGastado.setText(resourceMap.getString("jLabelGastado.text")); // NOI18N
        jLabelGastado.setName("jLabelGastado"); // NOI18N

        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        jLabelTeQuedan.setFont(resourceMap.getFont("jLabelTeQuedan.font")); // NOI18N
        jLabelTeQuedan.setText(resourceMap.getString("jLabelTeQuedan.text")); // NOI18N
        jLabelTeQuedan.setName("jLabelTeQuedan"); // NOI18N

        jButtonQueryPlayers.setText(resourceMap.getString("jButtonQueryPlayers.text")); // NOI18N
        jButtonQueryPlayers.setName("jButtonQueryPlayers"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 504, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabelGastado)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 147, Short.MAX_VALUE)
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabelTeQuedan)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButtonQueryPlayers)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 265, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonQueryPlayers)
                    .addComponent(jLabel2)
                    .addComponent(jLabelGastado)
                    .addComponent(jLabelTeQuedan)
                    .addComponent(jLabel4))
                .addContainerGap())
        );

        jLabelNameTeam.setFont(resourceMap.getFont("jLabelNameTeam.font")); // NOI18N
        jLabelNameTeam.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabelNameTeam.setText(resourceMap.getString("jLabelNameTeam.text")); // NOI18N
        jLabelNameTeam.setName("jLabelNameTeam"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jButtonSaveChange)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonExit))
                    .addComponent(jLabelNameTeam, javax.swing.GroupLayout.DEFAULT_SIZE, 540, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabelNameTeam)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonExit)
                    .addComponent(jButtonSaveChange))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonExit;
    private javax.swing.JButton jButtonQueryPlayers;
    private javax.swing.JButton jButtonSaveChange;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabelGastado;
    private javax.swing.JLabel jLabelNameTeam;
    private javax.swing.JLabel jLabelTeQuedan;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTableSoccerPlayers;
    // End of variables declaration//GEN-END:variables

    public void setFantasyTeamName( String name ) {
        jLabelNameTeam.setText( name );
    }

    public int getSelectedPosition() {
        return jTableSoccerPlayers.getSelectedRow();
    }

    public void setPlayerAtPosition(int position, SoccerPlayer soccerPlayer) {
        try {
            DefaultTableModel model = (DefaultTableModel) jTableSoccerPlayers.getModel();
            if (position >= 0 && position < 15) {
                model.setValueAt(soccerPlayer.getLastName() + ", " + soccerPlayer.getFirstName(), position, 1);
                model.setValueAt(soccerPlayer.getRealTeam().getName(), position, 2);
                model.setValueAt(soccerPlayer.getPrice(), position, 3);                

                soccerPlayers[position] = soccerPlayer;
            } else {
                int i = 0;
                String soccerPlayerPosition = soccerPlayer.getPosition();
                while (i < 15 && (soccerPlayers[i] != null || !model.getValueAt(i, 0).toString().startsWith(soccerPlayerPosition))) {
                    i++;
                }
                if (i < 15) {
                    model.setValueAt(soccerPlayer.getLastName() + ", " + soccerPlayer.getFirstName(), i, 1);
                    model.setValueAt(soccerPlayer.getRealTeam().getName(), i, 2);
                    model.setValueAt(soccerPlayer.getPrice(), i, 3);
                    soccerPlayers[i] = soccerPlayer;
                }
            }
            jTableSoccerPlayers.clearSelection();
        } catch (Exception ex) {
        }
    }

    public SoccerPlayer getPlayerAtPosition(int position) {
        if (position >= 0 && position < 15) {
            return soccerPlayers[position];
        }
        return null;
    }

    public List<SoccerPlayer> getSoccerPlayers() {
        LinkedList<SoccerPlayer> soccerPlayerList = new LinkedList<SoccerPlayer>();
        
        for (int i = 0; i < 15; i++) {
            if (soccerPlayers[i] != null ) {
                soccerPlayerList.add(soccerPlayers[i]);                
            }
        }
        return soccerPlayerList;
    }

    public boolean compararConEquiposAFA(String fantasyTeamName) {
        return true;
    }

    ;

    public void setLLevasGastado(int gastado) {
        this.jLabelGastado.setText(String.valueOf(gastado));
    }

    public void setTeQuedan(int quedan) {
        this.jLabelTeQuedan.setText(String.valueOf(quedan));
    }

    public void addQueryPlayersListener(ActionListener listener) {
        jButtonQueryPlayers.addActionListener(listener);
    }

    public void removeQueryPlayersListener(ActionListener listener) {
        jButtonQueryPlayers.removeActionListener(listener);
    }

    public void removeSaveListener(ActionListener listener) {
        jButtonSaveChange.removeActionListener(listener);
    }

    public void addSaveListener(ActionListener listener) {
        jButtonSaveChange.addActionListener(listener);
    }

    public Component asWidget() {
        return this;
    }

    public void addExitListener(ActionListener listener) {
        jButtonExit.addActionListener(listener);
    }

    public void removeExitListener(ActionListener listener) {
        jButtonExit.removeActionListener(listener);
    }

    public void showError(String errorMessage, String titleMessageWindow) {
        JOptionPane.showMessageDialog(this, errorMessage, titleMessageWindow, JOptionPane.ERROR_MESSAGE);
    }

    public void showOK(String okMessage, String titleMessageWindow) {
        JOptionPane.showMessageDialog(this, okMessage, titleMessageWindow, JOptionPane.INFORMATION_MESSAGE);
    }

    public void close() {
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setVisible(false);
    }

    public void loadPlayers( List<FantasyTeamPlayer> players ) {
        int def = 0, vol = 0, del = 0;

        Iterator<FantasyTeamPlayer> it = players.iterator();
        while (it.hasNext()) {
            FantasyTeamPlayer player = it.next();
            SoccerPlayer soccerPlayer = player.getSoccerPlayer();
            
            if (SoccerPlayer.GOALKEEPER_POSITION.equals( soccerPlayer.getPosition() )) {
                if (FantasyTeamPlayer.TITULAR_ROLE.equals( player.getRol() ))
                    setPlayerAtPosition( 0, soccerPlayer );
                else
                    setPlayerAtPosition( 11, soccerPlayer );

            } else if (SoccerPlayer.DEFENDER_POSITION.equals( soccerPlayer.getPosition() )) {
                if (FantasyTeamPlayer.TITULAR_ROLE.equals( player.getRol() ))
                    setPlayerAtPosition( 1 + def++, soccerPlayer );
                else
                    setPlayerAtPosition( 12, soccerPlayer );

            } else if (SoccerPlayer.MIDFIELDER_POSITION.equals( soccerPlayer.getPosition() )) {
                if (FantasyTeamPlayer.TITULAR_ROLE.equals( player.getRol() ))
                    setPlayerAtPosition( 5 + vol++, soccerPlayer );
                else
                    setPlayerAtPosition( 13, soccerPlayer );

            } else {
                if (FantasyTeamPlayer.TITULAR_ROLE.equals( player.getRol() ))
                    setPlayerAtPosition( 8 + del++, soccerPlayer );
                else
                    setPlayerAtPosition( 14, soccerPlayer );
            }
        }
    }

    public void showNotification( String notifiactionMessage, String notificationMessageTitle ) {
        JOptionPane.showMessageDialog( this,
                notifiactionMessage,
                notificationMessageTitle,
                JOptionPane.INFORMATION_MESSAGE);
    }

    public boolean showConfirmation( String notifiactionMessage ) {
        int confirm = JOptionPane.showConfirmDialog( this, notifiactionMessage, "Confirmación", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE );

        if (JOptionPane.YES_OPTION == confirm)
            return true;
        else
            return false;
    }
}
